package com.by.controller;

import com.by.bean.params.PurchaseQuery;
import com.by.bean.pucharse.Purchase;
import com.by.common.bean.PageBean;
import com.by.common.bean.ResultBean;
import com.by.common.controller.BaseController;
import com.by.common.exception.ValidateException;
import com.by.service.PurchaseService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.xml.bind.ValidationException;

@RestController
@Api(tags = "采购单管理")
@RequestMapping("/api")
public class PurchaseController extends BaseController {

    @Autowired
    PurchaseService purchaseService;
    @ApiOperation("采购单列表")
    @PostMapping("/list")
    public ResultBean<PageBean> query(@RequestBody PurchaseQuery query){
        PageBean bean=purchaseService.search(query);
        return success("采购单列表",bean);
    }

    @ApiOperation("保存采购单")
    @PostMapping("/purchase")
    public ResultBean save(@RequestBody Purchase purchase) {
        int rs = purchaseService.save(purchase);
        return saveResult(rs);
    }

    @ApiOperation("采购单详情")
    @GetMapping("/purchase")
    public ResultBean get(int id) {
        Purchase purchase = purchaseService.get(id);
        return success("采购单详情", purchase);
    }


    @PutMapping("/purchase")
    @ApiOperation("修改采购单")
    public ResultBean update(@Validated @RequestBody Purchase purchase, BindingResult result) {
        validate(result);
        if (null == purchase.getPurchaseDetailList() || purchase.getPurchaseDetailList().size() == 0)
            throw new ValidateException("purchaseDetailList", "采购明细不能为空！");
        purchase.getPurchaseDetailList().forEach(pur -> {
            if (null == pur.getGoodsname() || "".equals(pur.getGoodsname()))
                throw new ValidateException("goodsname", "商品名称不能为空！");
        });
        int rs = purchaseService.update(purchase);
        return updateResult(rs);
    }
    @ApiOperation("删除采购单")
    @GetMapping("/delete")
    //单个参数加文档注释 多个使用ApiImplicitParams对象
    @ApiImplicitParam(name = "id",value = "采购单id",required = true,dataTypeClass = Integer.class)
    public ResultBean delete( @RequestParam(name = "id",required = true) int id){
        int rs=purchaseService.delete(id);
        if(rs>0){
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
